<template>
  <div class="skill-manage-page">
    <div class="page-header">
      <h2>技能管理</h2>
      <p>为维修工分配和管理技能</p>
    </div>

    <div class="skill-manage-content">
      <!-- 左侧：维修工列表 -->
      <div class="worker-list-section">
        <a-card title="维修工列表" class="worker-list-card">
          <!-- 搜索表单 -->
          <div class="search-form">
            <a-input-search
              v-model:value="searchForm.keyword"
              placeholder="搜索维修工姓名或账号"
              enter-button="搜索"
              @search="handleSearch"
              style="margin-bottom: 16px"
            />
          </div>

          <!-- 维修工列表 -->
          <a-spin :spinning="workersLoading">
            <div class="worker-list">
              <div
                v-for="worker in workerList"
                :key="worker.userInfo.id"
                class="worker-item"
                :class="{ active: selectedWorker?.userInfo.id === worker.userInfo.id }"
                @click="selectWorker(worker)"
              >
                <div class="worker-info">
                  <div class="worker-name">{{ worker.userInfo.nickName }}</div>
                  <div class="worker-account">{{ worker.userInfo.accountName }}</div>
                  <div class="worker-skills">
                    <a-tag
                      v-for="skill in worker.skills"
                      :key="skill.categoryId"
                      size="small"
                      color="blue"
                    >
                      {{ skill.categoryName }}
                    </a-tag>
                    <span v-if="worker.skills.length === 0" class="no-skills">暂无技能</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-wrapper" v-if="workerList.length > 0">
              <a-button
                v-if="hasMoreWorkers"
                @click="loadMoreWorkers"
                :loading="loadingMore"
                block
                style="margin-top: 16px"
              >
                加载更多
              </a-button>
            </div>

            <a-empty v-if="!workersLoading && workerList.length === 0" description="暂无维修工" />
          </a-spin>
        </a-card>
      </div>

      <!-- 右侧：技能管理 -->
      <div class="skill-manage-section">
        <a-card title="技能管理" class="skill-manage-card">
          <template #extra v-if="selectedWorker">
            <a-button type="primary" @click="showAddSkillModal">
              <template #icon><PlusOutlined /></template>
              添加技能
            </a-button>
          </template>

          <div v-if="!selectedWorker" class="no-selection">
            <a-empty description="请选择一个维修工来管理技能" />
          </div>

          <div v-else class="worker-skill-manage">
            <!-- 维修工信息 -->
            <div class="worker-detail">
              <h3>{{ selectedWorker.userInfo.nickName }}</h3>
              <p>账号：{{ selectedWorker.userInfo.accountName }}</p>
              <p>邮箱：{{ selectedWorker.userInfo.email }}</p>
              <p>电话：{{ selectedWorker.userInfo.phoneNumber }}</p>
            </div>

            <!-- 当前技能列表 -->
            <div class="current-skills">
              <h4>当前技能</h4>
              <div class="skills-list">
                <div
                  v-for="skill in selectedWorker.skills"
                  :key="skill.categoryId"
                  class="skill-item"
                >
                  <div class="skill-info">
                    <div class="skill-name">{{ skill.categoryName }}</div>
                    <div class="skill-desc">{{ skill.categoryDescription }}</div>
                  </div>
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removeSkill(skill.categoryId)"
                    :loading="removingSkills.includes(skill.categoryId)"
                  >
                    移除
                  </a-button>
                </div>
                <a-empty v-if="selectedWorker.skills.length === 0" description="暂无技能" />
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 添加技能弹窗 -->
    <a-modal
      v-model:open="addSkillModalVisible"
      title="添加技能"
      @ok="handleAddSkill"
      @cancel="handleCancelAddSkill"
      :confirm-loading="addingSkill"
    >
      <div class="add-skill-form">
        <a-form :model="addSkillForm" layout="vertical">
          <a-form-item label="选择技能类别" required>
            <a-select
              v-model:value="addSkillForm.categoryId"
              placeholder="请选择技能类别"
              :options="availableCategoriesOptions"
              :field-names="{ label: 'categoryName', value: 'id' }"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getAllMaintenanceWorkers, addMaintenanceSkill, removeMaintenanceSkill } from '@/api/skill'
import { getCategoryList } from '@/api/category'
import type { UserSkillSummaryResponse, RepairCategory, MaintenanceSkillAddRequest, MaintenanceSkillRemoveRequest } from '@/types'

// 响应式数据
const workersLoading = ref(false)
const loadingMore = ref(false)
const workerList = ref<UserSkillSummaryResponse[]>([])
const selectedWorker = ref<UserSkillSummaryResponse | null>(null)
const hasMoreWorkers = ref(false)
const lastWorkerId = ref(0)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 添加技能相关
const addSkillModalVisible = ref(false)
const addingSkill = ref(false)
const addSkillForm = reactive({
  categoryId: undefined as number | undefined
})
const availableCategories = ref<RepairCategory[]>([])
const removingSkills = ref<number[]>([])

// 计算可用的技能类别（排除已有的，只显示启用的）
const availableCategoriesOptions = computed(() => {
  if (!selectedWorker.value) return []

  const existingCategoryIds = selectedWorker.value.skills.map(skill => skill.categoryId)
  return availableCategories.value
    .filter(category =>
      !existingCategoryIds.includes(category.id) && // 排除已有技能
      category.isActive === 1 // 只显示启用的类别
    )
    .map(category => ({
      id: category.id,
      categoryName: category.categoryName
    }))
})

// 页面初始化
onMounted(() => {
  fetchWorkers()
  fetchCategories()
})

// 获取维修工列表
const fetchWorkers = async () => {
  try {
    workersLoading.value = true
    const response = await getAllMaintenanceWorkers()

    if (response.code === 0) {
      workerList.value = response.data || []
      // 如果有搜索关键词，进行前端过滤
      if (searchForm.keyword) {
        workerList.value = workerList.value.filter(worker =>
          worker.userInfo.nickName.includes(searchForm.keyword) ||
          worker.userInfo.accountName.includes(searchForm.keyword)
        )
      }
    } else {
      message.error('获取维修工列表失败')
    }
  } catch (error) {
    console.error('获取维修工列表失败:', error)
    message.error('获取维修工列表失败')
  } finally {
    workersLoading.value = false
  }
}

// 获取维修类别列表（只获取启用的）
const fetchCategories = async () => {
  try {
    const response = await getCategoryList({
      pageSize: 100,
      current: 1,
      lastId: 0,
      isActive: 1 // 只获取启用的类别
    })
    if (response.code === 0 && response.data) {
      // 处理新的分页响应结构
      const pageData = response.data
      availableCategories.value = pageData.records || []
    }
  } catch (error) {
    console.error('获取维修类别失败:', error)
  }
}

// 搜索维修工
const handleSearch = () => {
  fetchWorkers()
}

// 选择维修工
const selectWorker = (worker: UserSkillSummaryResponse) => {
  selectedWorker.value = worker
}

// 加载更多维修工（暂时不实现，因为API返回所有数据）
const loadMoreWorkers = () => {
  // 当前API返回所有数据，暂不需要分页加载
}

// 显示添加技能弹窗
const showAddSkillModal = () => {
  addSkillForm.categoryId = undefined
  addSkillModalVisible.value = true
}

// 添加技能
const handleAddSkill = async () => {
  if (!selectedWorker.value || !addSkillForm.categoryId) {
    message.warning('请选择技能类别')
    return
  }

  try {
    addingSkill.value = true
    const request: MaintenanceSkillAddRequest = {
      userId: selectedWorker.value.userInfo.id,
      categoryId: addSkillForm.categoryId
    }

    const response = await addMaintenanceSkill(request)
    if (response.code === 0) {
      message.success('添加技能成功')
      addSkillModalVisible.value = false
      // 重新获取数据
      await fetchWorkers()
      // 更新选中的维修工信息
      const updatedWorker = workerList.value.find(w => w.userInfo.id === selectedWorker.value!.userInfo.id)
      if (updatedWorker) {
        selectedWorker.value = updatedWorker
      }
    } else {
      message.error(response.message || '添加技能失败')
    }
  } catch (error) {
    console.error('添加技能失败:', error)
    message.error('添加技能失败')
  } finally {
    addingSkill.value = false
  }
}

// 取消添加技能
const handleCancelAddSkill = () => {
  addSkillModalVisible.value = false
  addSkillForm.categoryId = undefined
}

// 移除技能
const removeSkill = async (categoryId: number) => {
  if (!selectedWorker.value) return

  try {
    removingSkills.value.push(categoryId)
    const request: MaintenanceSkillRemoveRequest = {
      userId: selectedWorker.value.userInfo.id,
      categoryId
    }

    const response = await removeMaintenanceSkill(request)
    if (response.code === 0) {
      message.success('移除技能成功')
      // 重新获取数据
      await fetchWorkers()
      // 更新选中的维修工信息
      const updatedWorker = workerList.value.find(w => w.userInfo.id === selectedWorker.value!.userInfo.id)
      if (updatedWorker) {
        selectedWorker.value = updatedWorker
      }
    } else {
      message.error(response.message || '移除技能失败')
    }
  } catch (error) {
    console.error('移除技能失败:', error)
    message.error('移除技能失败')
  } finally {
    removingSkills.value = removingSkills.value.filter(id => id !== categoryId)
  }
}
</script>

<style scoped>
.skill-manage-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
}

.skill-manage-content {
  display: flex;
  gap: 24px;
  height: calc(100vh - 200px);
}

.worker-list-section {
  flex: 1;
  min-width: 400px;
}

.skill-manage-section {
  flex: 1;
  min-width: 400px;
}

.worker-list-card,
.skill-manage-card {
  height: 100%;
}

.worker-list {
  max-height: calc(100vh - 350px);
  overflow-y: auto;
}

.worker-item {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.worker-item:hover {
  border-color: #1890ff;
  background-color: #f6ffed;
}

.worker-item.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.worker-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.worker-account {
  color: #666;
  font-size: 12px;
  margin-bottom: 8px;
}

.worker-skills {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-skills {
  color: #999;
  font-size: 12px;
}

.no-selection {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.worker-detail {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
  margin-bottom: 24px;
}

.worker-detail h3 {
  margin: 0 0 8px 0;
}

.worker-detail p {
  margin: 4px 0;
  color: #666;
}

.current-skills h4 {
  margin-bottom: 16px;
}

.skills-list {
  max-height: calc(100vh - 500px);
  overflow-y: auto;
}

.skill-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  margin-bottom: 8px;
}

.skill-info {
  flex: 1;
}

.skill-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.skill-desc {
  color: #666;
  font-size: 12px;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 16px;
}

.add-skill-form {
  padding: 16px 0;
}
</style>
